// pages/login/login.js
import config from "../../config.js";
const openIdUrl = config;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: "",
    time: 60,
    tel: "",
    password: '',
    loginType: 1,
    isGetCode: false,
    sendSatus: "发送验证码",
    show: true,
  },

  typeSelect: function(e) {
    let num = e.currentTarget.dataset.id;
    this.setData({
      loginType: num
    })
  },

  bindCode: function(e) {
    var value = e.detail.value
    var pos = e.detail.cursor
    console.log(value);
    this.setData({
      code: value
    })
  },

  bindPassword: function(e) {
    var value = e.detail.value
    var pos = e.detail.cursor
    console.log(value);
    this.setData({
      password: value
    })
  },

  bindTel: function(e) {
    var value = e.detail.value
    var pos = e.detail.cursor
    console.log(value);
    this.setData({
      tel: value
    })
  },



  //手机号校验
  telCheck: function(tel) {
    var tel = tel,
      reg = reg = /^1[123456789]\d{9}$/;
    if (tel == '') {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return false
    } else if (tel.length != 11) {
      wx.showToast({
        title: '手机号格式有误！',
        icon: 'none',
        mask: true,
        duration: 1500
      })
      return false;
    }
    if (!reg.test(tel)) {
      wx.showToast({
        title: '手机号格式有误！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    return true;
  },


  //验证码按钮状态
  changeCodeStatus: function() {
    var flag = this.data.isGetCode,
      that = this;

    var timer = setInterval(function() {
      if (that.data.time > 0) {
        that.setData({
          time: (that.data.time - 1),
        })
        that.setData({
          sendSatus: that.data.time + "秒后重新获取",
        })
      } else {
        clearInterval(timer);
        that.setData({
          time: 60, //验证码间隔
          isGetCode: false
        })
        that.setData({
          sendSatus: "请获取验证码",
        })
      }
    }, 1000);
  },


  //发送验证码
  getCode: function() {
    var tel = this.data.tel,
      flag_tel = this.telCheck(tel),
      flag_getting = this.data.isGetCode,
      that = this;
    //手机号格式不对或者正在发送验证码时返回
    if (!flag_tel || flag_getting) return false;

    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.getVerifyCode,
      header: {
        'content-type': 'application/json',
      },
      data: {
        telephone: tel,
        type: 0
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if(res.data.status==200){
          wx.setStorageSync("session", res.data.data);
        }else{
          wx.setStorageSync("session", null);
        }

        wx.showToast({
          //title: res.data.message + "",
          title: res.data.message,
          // image:'../../vendor/assets/images/logo.png',
          icon: 'none',
          duration: 2000
        })
        //更改倒计时；
        that.setData({
          isGetCode: true
        })
        that.changeCodeStatus();
      }
    })
    return true;
  },




  //登录
  login: function() {
    //链接即时通讯服务器
    var phoneName = this.data.tel;
    var phoneCode = this.data.code;
    var password = this.data.password;
    var loginType = this.data.loginType;
    var flag_tel = this.telCheck(phoneName);
    var that = this;
    console.log(phoneName);
    if (flag_tel) {
      //验证码登录
      if (loginType == 1) {
        if (phoneCode == '') {
          wx.showToast({
            title: '请输入验证码',
            icon: 'none',
            mask: true,
            duration: 1000,
            mask: true
          })
        } else {
          var openId = wx.getStorageSync("openID");
          var model = wx.getStorageSync("model");
          wx.showLoading({
            title: '登录中',
            mask: true,
          })
          wx.request({
            url: openIdUrl.loginUrl,
            header: {
              "Content-Type": "application/x-www-form-urlencoded",
              "Cookie": wx.getStorageSync("session")
            },
            data: {
              telephone: phoneName,
              loginType: loginType,
              verifyCode: phoneCode,
              model: model,
              openId: openId,
              password: ''
            },
            dataType: 'json',
            method: "POST",
            success: function(res) {
              console.log(res.data);
              if (res.data.status == 200) {
                wx.hideLoading();
                wx.showToast({
                  title: res.data.message + "",
                  icon: 'none',
                  mask: true,
                  duration: 2000
                })

                that.getUserInfo(res.data.data.userId);

              } else {
                wx.hideLoading();
                wx.showToast({
                  title: res.data.message + "",
                  icon: 'none',
                  mask: true,
                  duration: 2000
                })
              }
            }
          })
        }

        //密码登录
      } else if (loginType == 2) {
        if (password == '') {
          wx.showToast({
            title: '请输入密码',
            icon: 'none',
            mask: true,
            duration: 1000,
            mask: true,
            password: ''
          })
        } else {
          var openId = wx.getStorageSync("openID");
          var model = wx.getStorageSync("model");
          wx.showLoading({
            title: '登录中',
            mask: true,
          })
          wx.request({
            url: openIdUrl.loginUrl,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Cookie': wx.getStorageSync("session")
            },
            data: {
              telephone: phoneName,
              loginType: loginType,
              password: password,
              model: model,
              openId: openId,
            },
            method: "POST",
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Cookie': wx.getStorageSync("session")
            },
            success: function(res) {
              console.log(res.data);
              if (res.data.status == 200) {
                wx.hideLoading();
                wx.showToast({
                  title: res.data.message + "",
                  icon: 'none',
                  mask: true,
                  duration: 2000
                })

                //保存session
                wx.setStorageSync("session", res.data.session);
                that.getUserInfo(res.data.userId);

              } else {
                wx.hideLoading();
                wx.showToast({
                  title: res.data.message + "",
                  icon: 'none',
                  mask: true,
                  duration: 2000
                })
              }
            }
          })
        }
      }
    }
  },


  getUserInfo: function() {
    wx.showLoading({
      title: '获取用户信息...',
    })
    var sessionId = wx.getStorageSync("session");
    console.log(sessionId);
    wx.request({
      url: openIdUrl.getUserInfo,
      header: {
        'content-type': 'application/json',
        'Cookie': sessionId
      },
      success: function(res) {
        console.log(res.data.data);
        wx.hideLoading();
        if (res.data.data != null && res.data.data != '') {

          // wx.setStorageSync("session", res.data.data);
          wx.showToast({
            title: "登录成功",
            icon: 'success',
            duration: 1200
          })
          //保存userInfo;
          var userInfo = res.data.data;
          //处理银行卡
          /**var cardNo = userInfo.membershipcard.cardNo;
          cardNo = cardNo.substring(0, 4) + "********" + cardNo.substring(cardNo.length - 4, cardNo.length);
          console.log(cardNo);
          userInfo.cardNumber = cardNo;
          console.log(userInfo);**/
          wx.setStorageSync("user", userInfo);

          //与管家聊天封装
          var chatUser = {
            'accountByAid': {
              'name': userInfo.housekeeper.name
            }
          };
          wx.setStorageSync("chatUser", chatUser);
          if (userInfo.accountType.typeId == 1) {
            //普通用户跳转；
            console.log("普通用户跳转");
            setTimeout(function() {
              wx.switchTab({
                url: '../index/index',
              })
            }, 1200);
          } else {
            //管家跳转；
            console.log("管家跳转");
            setTimeout(function() {
              wx.reLaunch({
                url: '../gjIndex/gjindex/gjindex',
              })
            }, 1200);
          }

          var pare = {};

          pare['userId'] = userInfo.aid
          pare['type'] = "handed"
          console.log(pare);

          wx.sendSocketMessage({
            data: JSON.stringify(pare)
          })
          console.log("发送完成" + pare);

        } else {

        }
      },
      fail: function() {
        console.log("111");
        wx.hideLoading();
      }
    })
  },



})